package com.crimsec.utils.snmp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;

/**
 * $Id$
 */
public class Utils implements IDefaults {

    private Properties props = new Properties();
    ;
    private Logger log = Logger.getLogger("snmp.Utils");
    private Map<String, String> defaults = new HashMap<String, String>();

    /**
     * @param other propeties for search namespace
     * @param namespace name (don't use wildchars)
     * @return a new Properties with keys(an their values) who names start with
     * given namesapace
     */
    public static Properties getPropertiesForNamespace(String namespace, Properties other) {
        if (other != null) {
            Properties result = new Properties();
            /*
             body {
             font-size: 18px;
             font-family: AGForeignerLightC,Trebuchet MS,Arial,Sans-Serif;
             line-height: 1.3;
             }*/

            Set<String> keys = other.stringPropertyNames();
            for (String key : keys) {
                if (key.startsWith(namespace)) {
                    result.put(key, other.getProperty(key));
                }
            }
            return result;
        } else {
            return null;
        }
    }

    public Utils(String name) throws IOException {
        loadProps(name);
    }

    public Utils() throws IOException {
        loadFromResources(PROPSNAME);
    }

    private void loadProps(String name) throws IOException {
        try {
            loadFromURL(name);
        } catch (IOException e) {
            log.warn("configuration file not found or invalid:" + e.getMessage());
            loadFromResources(PROPSNAME);
        }
    }

    private void constructDefauls() {
        defaults.put(LOGBASE, "/var/log/snmp");
    }

    private void loadFromURL(String file) throws IOException {
        log.info("attempt to load a configuration file with the specified url:" + file);
        URL url = new URL(file);
        props.load(new InputStreamReader(url.openStream()));
    }

    private void loadFromResources(String resName) throws IOException {
        //TODO: разобраться с заргузкой ресурсов при любых обстоятельствах, может подсмотреть в log4j сырцах
        log.info("load a configuration file from resources");
        InputStream i = Class.class.getResourceAsStream("/" + resName);
        InputStreamReader ir = new InputStreamReader(i);
        props.load(ir);
    }

    public Properties getJPAHibernateProps() {
        return getPropertiesForNamespace("hibernate", props);
    } 

    public String getLogBase() {
        return getValue(LOGBASE);
    }

    private String getValue(String propName) {
        String candidate = props.getProperty(propName);
        if ((candidate == null) || (candidate.isEmpty())) {
            log.warn(propName + " is empty or not found,so using defaults");
            candidate = defaults.get(propName);
        }
        return candidate;
    } 

    public static String constructSafeDateString(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
        return sdf.format(date);

    }

    public static String constructSafeDateString() {
        return constructSafeDateString(new Date());
    }
    
    public static String constLogDelimLine(String msg) {
        return IDefaults.LOGDELIMITER+msg+IDefaults.LNMARK;
    }
}
